import time

from qturboframe.lib.utils.by import By
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.lib.utils.controlname import ControlName
from qturboframe.lib.ranorex.win_control.text import Text as WinText
from qturboframe.lib.ranorex.exceptions import CsClientError
from qturboframe.lib.ranorex.win_control.radio_button import RadioButton as WinRadioButton
from qturboframe.lib.ranorex.win_control.control import Control

from qturboframe.public_ui.ucf_wpf.basecontrol import BaseControl

class RadioButton(BaseControl):
    """
    ucf wpf的单选控件

    :Attributes:
     - _driver: 控件所在的当前Control对象
     - radioes: 按照locator查找到的所有的单选控件对象
     - timeout: 步骤操作的超时时间

    :Raises
     - CsClientError 没有找到控件异常
     - AttributeError 当element_para类型不正确时则抛出此异常

    :Example:
     - 例1: RadioButton(control)
     - 例2: RadioButton({By.RANOREXPATH:'ranorexpath'})
     - 例3: RadioButton({By.TEXT:'导入'})
     - 例4: RadioButton({By.XPATH:'xpath','text':'文本信息'})
     - 例5: RadioButton({By.AUTOMATIONID:'automationid','text':'文本信息'}, father=driver)
    """
    def __initialize(self, element_para, father=None, timeout=10000):
        self.timeout = timeout

        if isinstance(element_para, Control):
            self._control = element_para
            self._driver = Control(element_para.control)
            self.xpath = self._control.get_path()
        elif hasattr(element_para, "_control") and isinstance(element_para._control, Control):
            self._control = element_para._control
            self._driver = Control(element_para._control.control)
            self.xpath = self._control.get_path()
        elif not isinstance(element_para, dict):
            message = 'element_para参数类型不正确！'
            raise CsClientError(CustomError.Error_EQ03008001_Parameter_InCorrect, message)
        else:
            if father is None:
                message = '未定位元素，father参数不能为None！'
                raise CsClientError(CustomError.Error_EQ03008001_Parameter_InCorrect, message)
            if isinstance(father, Control):
                self._driver = father
                self.timeout = timeout
            else:
                message = 'father参数类型不正确！'
                raise CsClientError(CustomError.Error_EQ03008001_Parameter_InCorrect, message)

            element_by = None
            element_value = None
            assist = ''
            if isinstance(element_para, dict) and By.AUTOMATIONID in element_para:
                element_by = By.XPATH
                element_value = ".//*[@automationid='{}']".format(element_para.get(By.AUTOMATIONID))
            else:
                key_list = [By.XPATH, By.RANOREXPATH]
                for key, value in element_para.items():
                    if key.lower() in key_list:
                        element_by = key
                        element_value = value
                    else:
                        assist += '{}:{},'.format(key, value)
                assist = assist.strip(',')

            self.controls = father.find_elements_by_attribute(
                element_by, element_value, assist, self.timeout)
            self.xpath = element_value
            for control in self.controls:
                if control.is_visible():
                    self._control = control
                    break
            else:
                raise CsClientError(CustomError.Error_EQ03001000_Cannot_Find_Element,"按照此路径{}没有找到可见的控件".format(str(element_para)))

    def __init__(self, element_para, father=None, timeout=10000):
        # super().__init__(element_para, father, timeout)
        self.__initialize(element_para, father, timeout=timeout)

        self.radio_buttons = []
        for control in self.controls:
            if control.get_control_name()==ControlName.RADIOBUTTON:
                self.radio_buttons.append(WinRadioButton(control.control))
            else:
                radio_button_controls = control.find_elements_by_attribute("xpath",".//radiobutton", timeout=self.timeout)
                for radio_button_control in radio_button_controls:
                    self.radio_buttons.append(WinRadioButton(radio_button_control.control))

        if len(self.radio_buttons) == 0:
            raise CsClientError(CustomError.Error_EQ03001000_Cannot_Find_Element,"按照此路径{}没有找到可见的RadioButton控件".format(str(element_para)))

    def check_radio_button(self, text):
        """
        wpf ucf 根据text选中某一个单选框

        :Args:
         - text: checkbox的文本

        :Example:
         - 例1: radio_button.check_radio_button('单选框')
        """
        for radio_button in self.radio_buttons:
            xpath = ".//text[@type='TextBlock']"
            text_control = radio_button.find_element_by_attribute(By.XPATH, xpath, timeout=self.timeout)

            if WinText(text_control.control).get_text().strip() == text.strip():
                if not radio_button.is_checked():
                    radio_button.select()
                break
        else:
            raise CsClientError(CustomError.Error_EQ03001000_Cannot_Find_Element,"没有找到名为{}的radiobutton".format(text))


    def uncheck_radio_button(self, text):
        """
        wpf ucf 根据text取消选择某一个单选框

        :Args:
         - text: checkbox的文本

        :Example:
         - 例1: radio_button.uncheck_radio_button('复选框 ')
        """
        for radio_button in self.radio_buttons:
            xpath = ".//text[@type='TextBlock']"
            text_control = radio_button.find_element_by_attribute(By.XPATH, xpath,timeout=self.timeout)

            if WinText(text_control.control).get_text().strip() == text.strip():
                if radio_button.is_checked():
                    radio_button.select()
                break

    def get_checked_radio(self):
        """
        wpf ucf 根据text取消选择某一个单选框

        :Args:
         - text: checkbox的文本

        :Example:
         - 例1: radio_button.get_checked_radio('复选框 ')
        """
        for radio_button in self.radio_buttons:
            if radio_button.is_checked():
                xpath = ".//text[@type='TextBlock']"
                text_control = radio_button.find_element_by_attribute(By.XPATH, xpath,timeout=self.timeout)
                return WinText(text_control.control).get_text().strip()

        return ""

